//
//  LemonIndexHeaderView.swift
//  zhonglb_iOS
//
//  Created by lxm on 2021/12/22.
//

import UIKit
protocol LemonIndexHeaderViewDelegate : NSObjectProtocol {
    func shouldSelect(indexView : LemonIndexHeaderView, indexpath : IndexPath) -> Bool
    func didSelect(indexView : LemonIndexHeaderView, indexpath : IndexPath)
}

extension LemonIndexHeaderViewDelegate {
    func shouldSelect(indexView : LemonIndexHeaderView, indexpath : IndexPath) -> Bool {
        return true
    }
    
    func didSelect(indexView : LemonIndexHeaderView, indexpath : IndexPath) {}
}

class LemonIndexHeaderView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    //MARK: --------------------属性--------------------
    var data = [String]() {
        didSet {
            collectionView.reloadData()
        }
    }
    
    var currentIndex = 0
    
    var lineView = UIView().then { v in
        v.backgroundColor = "#DE3F26".zm.hex()
        v.frame = CGRect(x: 0, y: 0, width: 80, height: 34)
        v.isUserInteractionEnabled = false
    }
    
    weak var delegate : LemonIndexHeaderViewDelegate?
    
    var config = LemonIndexHeaderConfig()

    //MARK: --------------------UI控件--------------------
    var collectionView : UICollectionView!
    //MARK: --------------------生命周期--------------------
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
        bindAction()
        addConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setUI()
        bindAction()
        addConstraints()
    }

    //MARK: --------------------UI--------------------
    func setUI() {
        let layout = UICollectionViewFlowLayout()
        collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
        addSubview(lineView)
        addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        backgroundColor = .clear
        collectionView.register(NormalItem.self, forCellWithReuseIdentifier: "NormalItem")
        RealLineViewScrolleToIndex(index: currentIndex, animation: false)
        
        // lineView
    }
    
    func fillUI() {
        lineView.layer.cornerRadius = zm.height / 2
        lineView.zm.setHeight(zm.height)
    }
    
    func addConstraints() {
     
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        collectionView.frame = bounds
        fillUI()
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
    }
    
    func RealLineViewScrolleToIndex(index: Int, animation: Bool) {
        let indexPath = IndexPath.init(row: index, section: 0)
        guard let cell = collectionView.cellForItem(at: indexPath) as? NormalItem,
              let attri = collectionView.layoutAttributesForItem(at: indexPath),
              let oldCell = collectionView.cellForItem(at: IndexPath.init(row: currentIndex, section: 0)) as? NormalItem else {return}
        let center = attri.frame.size.width / 2 + attri.frame.origin.x
        if animation {
            UIView.animate(withDuration: 0.2) {
                self.lineView.zm.setCenterX(center)
                oldCell.label.textColor = self.config.normalTitleColor
                oldCell.label.font = self.config.normalTitleFont
                cell.label.textColor = self.config.selectTitleColor
                cell.label.font = self.config.selectTittleFont
            }
        } else {
            self.lineView.zm.setCenterX(cell.center.x)
        }
        
        collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredVertically, animated: animation)
        currentIndex = index
    }
    //MARK: --------------------delegate--------------------
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        data.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NormalItem", for: indexPath) as! NormalItem
        let select = currentIndex == indexPath.row
        cell.label.text = data[indexPath.row]
        cell.label.textColor = select ? config.selectTitleColor : config.normalTitleColor
        cell.label.font = select ? config.selectTittleFont : config.normalTitleFont
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let delegate = delegate, delegate.shouldSelect(indexView : self, indexpath: indexPath) {
            RealLineViewScrolleToIndex(index: indexPath.row, animation: true)
            delegate.didSelect(indexView : self, indexpath: indexPath)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.zm.size.width / CGFloat(data.count)
        let height = collectionView.zm.size.height
        return CGSize(width: width, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

//MARK: NormalItem class
extension LemonIndexHeaderView {
    class NormalItem : UICollectionViewCell {
        var label = UILabel()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setUI()
        }
        
        func setUI() {
            contentView.addSubview(label)
            backgroundColor = .clear
            label.snp.makeConstraints { make in
                make.center.equalToSuperview()
//                make.edges.equalToSuperview()
            }
        }
    }
    
    class LemonIndexHeaderConfig {
        var selectTitleColor = "#ffffff".zm.hex()
        var normalTitleColor = "#999999".zm.hex()
        var normalTitleFont = UIFont.systemFont(ofSize: 14, weight: .regular)
        var selectTittleFont = UIFont.systemFont(ofSize: 14, weight: .medium)
    }
}


